package com.fivec.javaproject.generatebitaddress.code.tools;

import java.util.Arrays;

/**
 * @author wangyizhu
 * @version "1.8.0_131"
 * @email 2641956765@qq.com
 * @desc:
 * @Time 2021/12/07 13:55
 */
public class IsValid {
    /**
     * 该方法用于判断生成的比特币地址是否有效
     * @param address
     * @return
     */
    public static boolean Isvalidforadress(String address) {
        //将地址进行base58反编码，生成的其实是version+Pub Key hash+ checksum这25个字节
        byte[] version_public_checksumBytes = Base58Util.decode(address);
        int len = version_public_checksumBytes.length;
        //取version_public_checksumBytes后4个字节
        byte[] checkSumBytes = Arrays.copyOfRange(version_public_checksumBytes, len - 4, len);
        //取version_public_checksumBytes前21字节
        byte[] ver = Arrays.copyOfRange(version_public_checksumBytes, 0, len - 4);
        //取ver进行两次sha256哈希运算，取第二次结果值的前4个字节
        byte[] hash1 = StaticMethod.getHash256(ver);
        byte[] hash2 = StaticMethod.getHash256(hash1);
        byte[] checkBytes = Arrays.copyOfRange(hash2, 0, 4);
        //将checkSumBytes与checkBytes比较，如果一致则说明地址有效，返回true
        checkBytes.equals(checkSumBytes);
        return Arrays.equals(checkSumBytes, checkBytes);
    }
}
